﻿using System;
using System.Xml.Linq;
using System.Reflection;

using Game;
using Engine;
using GameEntitySystem;

namespace ApiToolkit
{
	public class StringPropertyEditor : CanvasWidget
	{
		public class PropertyEditor_String : PropertyEditor
		{
			public PropertyEditor_String(int content, string targetProperty) : base(content, targetProperty)
			{
			}
			
			#region Behaviors

			class CategoryPropertyBehavior : IPropertyBehavior
			{
				public ApplyStatus Apply(PropertyEditor editor, object value)
				{
					editor.TargetPropertyValue = value;
					return ApplyStatus.Succeed;
				}
			}
			class BehaviorPropertyBehavior : IPropertyBehavior
			{
				public ApplyStatus Apply(PropertyEditor editor, object value)
				{
					bool isAllExist = true;
					var values = value.ToString().Split(',');
					foreach (var behavior in ((DatabaseManager.DatabaseNode.Element("DatabaseObjects").FirstNode.NextNode as XElement).FirstNode as XElement).Elements())
					{
						if(!isAllExist)
						{
							continue;
						}
						bool isExist = false;
						foreach(var val in values)
						{
							if (isExist || behavior.Attribute("Name").Value == value.ToString())
							{
								isExist = true;
							}
						}
						if(!isExist)
						{
							isAllExist = false;
						}
						
					}
					if (isAllExist)
					{
						editor.TargetPropertyValue = value;
					}
					
					return ApplyStatus.Failed;
				}
			}
			#endregion
			
			#region Behavior
			private IPropertyBehavior getProperty(string propName)
			{
				if(propName == "Behaviors")
				{
					return new BehaviorPropertyBehavior();
				}
				return new DefaultBehavior();
			}
			private IPropertyBehavior propertyBehavior = null;
			internal override IPropertyBehavior PropertyBehavior
			{
				get
				{
					if (propertyBehavior == null)
					{
						propertyBehavior = getProperty(TargetPropertyName);
					}
					return propertyBehavior;
				}
			}
			#endregion
		}

		#region MemberWidgets
		TextBoxWidget TextBox;
		string Text
		{
			get => TextBox.Text;
			set => TextBox.Text = value;
		}

		BevelledButtonWidget ApplyButton;
		#endregion MemberWidgets

		PropertyEditor_String editor;
		ContainerWidget Parent;
		public StringPropertyEditor(int content, string targetProperty, ContainerWidget parent) : base()
		{
			editor = new PropertyEditor_String(content,targetProperty);
			if(editor.TargetPropertyValue == null) editor.TargetPropertyValue = string.Empty;
			
			
			Parent = parent;
			XElement widgetNode = ContentManager.Get<XElement>("Widgets/StringPropertyEditor");
			LoadContents(this, widgetNode);

			ApplyButton = Children.Find<BevelledButtonWidget>("ApplyButton");
			TextBox = Children.Find<TextBoxWidget>("TextBox");
			TextBox.Text = editor.TargetPropertyValue.ToString();
		}

		public override void Update()
		{
			if (ApplyButton.IsClicked)
			{
				Apply();
			}
		}
		void Apply()
		{
			editor.Apply(Text);
		}
	}
} 